package com.ray.tcc.login.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ray.api.service.UcenterApiService;
import com.ray.auth.system.emun.ManagerType;
import com.ray.auth.system.emun.UserType;
import com.ray.auth.system.table.entity.Notice;
import com.ray.auth.system.table.entity.Organization;
import com.ray.auth.system.table.entity.User;
import com.ray.auth.system.table.entity.Work;
import com.ray.sso.SSOCommonValue;
import com.xiaoleilu.hutool.util.ObjectUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.zjhc.flyhong.common.datastructure.TreeNode;
import com.zjhc.flyhong.common.function.error.MessageHandle;
import com.zjhc.flyhong.common.function.operator.LoginUser;
import com.zjhc.flyhong.common.function.operator.PageDto;
import com.zjhc.flyhong.common.util.Md5Util;
import com.zjhc.flyhong.common.web.Result;
import com.zjhc.flyhong.redis.DefaultRedisService;
import com.zjhc.shiro.login.ShiroLogin;
import com.zjhc.web.util.ContextHolderUtils;

/**
 * <h1>用户登录 控制器</h1>
 * 
 * @创建人 ray
 * @创建时间 2017-06-12
 * @版本 1.0
 * @重要修改备注
 * 
 */
@Controller
@RequestMapping("/")
public class LoginController {
	 @Autowired
	 private UcenterApiService  ucenterApiService;
	@Autowired
	private DefaultRedisService defaultRedisService;

	
	
	/**
	 * @param userName
	 * @param passWord
	 * @return
	 */
	@RequestMapping(value = "ssoLogin")
	public ModelAndView doSsoLogin(HttpServletRequest rquest, HttpServletResponse respose,
			ModelAndView modelAndView) {
		//session 存在 不用登录--->调用登录方法必须校验
		LoginUser loginUser = null;
		//登录ssoSessionId;
		String ssoSessionid = rquest.getParameter("ssoSessionId");
		//登录用户
		String userName = rquest.getParameter("userName");
		//秘钥
		String token = rquest.getParameter("token");
		//单点登录状态
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		//不开启的时候
		if(!ssoStatus){
			modelAndView.setViewName("login");
			return modelAndView;
		}
		//session校验
		if(StrUtil.isBlank(ssoSessionid)){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
		
         if(StrUtil.isBlank(userName)){
        	String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
		}
         
       //token校验
 		if(StrUtil.isBlank(token)){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
		
 		//校验token 是否允许
 		String ssoKey = MessageHandle.getMsgByKey("sso.key");
 		
 		if(!StrUtil.equals(token, Md5Util.getMd5(ssoKey+ssoSessionid))){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
 		
 		//sso校验
 		String code = defaultRedisService.get(SSOCommonValue.SSO_SESSION_ID+"_"+ssoSessionid);
 		if(StrUtil.isBlank(code)){
 			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
 			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
 			return new ModelAndView("redirect:"+loginUrl);
 		}
 		
     	ShiroLogin login = new ShiroLogin();
     	//校验本地权限
     	boolean loginStatus  = login.doSsologin(userName, ssoSessionid);
     	if(loginStatus){
     		loginUser = new LoginUser();
			// 获取用户信息
			Result<User> userResult = ucenterApiService.queryUser(userName);
			if(userResult.codeSuccess()){
				User user = userResult.getData();
				if (ObjectUtil.isNotNull(user)) {
					loginUser.setExtendUser(user);
					loginUser.setUserName(user.getUserName());
					loginUser.setLoginName(userName);
					loginUser.setUserId(user.getUserId());
					//超级管理员
					if(StrUtil.equals(user.getManagerType(), ManagerType.SUPER.getType())){
						loginUser.setSuperManager(true);
					}
					//超级管理员
					if(StrUtil.equals(user.getUserType(), UserType.MANAGER.getType())){
						loginUser.setManager(true);
					}
					
					// 获取部门信息
					Result<Organization> deptResult = ucenterApiService.queryOrgByOrgCode(user.getOrgCode());
					if(deptResult.codeSuccess()){
						Organization dept = deptResult.getData();
						if (ObjectUtil.isNotNull(dept)) {
							loginUser.setDeptCode(dept.getOrgId());
							loginUser.setDeptName(dept.getOrgName());
						}
					}else{
						//登录失败
						String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
						loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
						return new ModelAndView("redirect:"+loginUrl);
					}
					
					// 获取所属组织信息
					Result<Organization> orgResult  = ucenterApiService.queryOrgByTenantId(user.getTenantId());
					if(deptResult.codeSuccess()){
						Organization org = orgResult.getData();
						if (ObjectUtil.isNotNull(org)) {
							loginUser.setOrgCode(org.getOrgId());
							loginUser.setOrgName(org.getOrgName());
							loginUser.setTenantId(org.getTenantId());
						}
					}else{
						//登录失败
						String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
						loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
						return new ModelAndView("redirect:"+loginUrl);
					}
					
				}
			}else{
				//登录失败
				String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
				loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
				return new ModelAndView("redirect:"+loginUrl);
			}
		}else{
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
         
		// 信息放入session
		ContextHolderUtils.setLoginUser(loginUser);
		Result<List<TreeNode>> rs =  ucenterApiService.queryUserHomeMenu(MessageHandle.getMsgByKey("app.id"),loginUser);
		if(rs.codeSuccess()){
			modelAndView.addObject("menus", rs.getData());
		}
		//加载个人工作任务
		PageDto<Work> dto = new PageDto<Work>(1, 10, null);
	    dto = ucenterApiService.queryMyTodoWork(new Work(), dto, loginUser);
	    modelAndView.addObject("works", dto);
	    //加载通知信息
	    PageDto<Notice> noticePagedto = new PageDto<Notice>(1, 10, "CREATE_TIME desc");
	    noticePagedto = ucenterApiService.queryNotice(new Notice(), noticePagedto, loginUser);
	    modelAndView.addObject("notices", noticePagedto);
		modelAndView.setViewName("index");
		return modelAndView;
	}
	
	
	
	
	@RequestMapping(value = "index")
	public ModelAndView doIndex(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		LoginUser loginUser = ContextHolderUtils.getLoginUser();
		if (ObjectUtil.isNotNull(loginUser)) {
			Result<List<TreeNode>> rs =  ucenterApiService.queryUserHomeMenu(MessageHandle.getMsgByKey("app.id"),loginUser);
			if(rs.codeSuccess()){
				modelAndView.addObject("menus", rs.getData());
			}
			//加载个人工作任务
			PageDto<Work> dto = new PageDto<Work>(1, 10, null);
		    dto = ucenterApiService.queryMyTodoWork(new Work(), dto, loginUser);
		    modelAndView.addObject("works", dto);
		    //加载通知信息
		    PageDto<Notice> noticePagedto = new PageDto<Notice>(1, 10, "CREATE_TIME desc");
		    noticePagedto = ucenterApiService.queryNotice(new Notice(), noticePagedto, loginUser);
		    modelAndView.addObject("notices", noticePagedto);
			modelAndView.setViewName("index");
			return modelAndView;
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	

	@RequestMapping(value = "view")
	public ModelAndView doView(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		//使用sso登录的时候 取消本地登录
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		
		if(ssoStatus){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			return new ModelAndView("redirect:"+loginUrl);
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping(value = "logout")
	public ModelAndView logout(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		 Subject subject = SecurityUtils.getSubject();  
	    if (subject.isAuthenticated()) {  
	        subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存  
	    }  
	    //使用sso登录的时候 取消本地登录
		Boolean ssoStatus = new Boolean(MessageHandle.getMsgByKey("app.sso"));
		if(ssoStatus){
			String loginUrl = MessageHandle.getMsgByKey("sso.login.url");
			loginUrl+="?appid="+MessageHandle.getMsgByKey("app.id");
			loginUrl+="&logout=logout";
			return new ModelAndView("redirect:"+loginUrl);
		}
		modelAndView.setViewName("login");
		return modelAndView;
	}
	
	@RequestMapping(value = "main")
	public String doMain(HttpServletRequest rquest, HttpServletResponse respose, ModelAndView modelAndView) {
		return "main";
	}

}
